import JSEncrypt from "encryptlong-telen";
export default class RsaUtil {
  static jsEncrypt = new JSEncrypt();
  // static jsEncrypt = new JSEncrypt({
  //   // default_key_size: 2048,
  // });

  /**
   * js加密
   *
   * @param text  明文
   * @param publicKey 请求公钥
   * @returns {*}
   */
  static encrypt = (text: string, publicKey: string): string => {
    if (text === "" || text === null || text === undefined) {
      return text;
    }
    try {
      RsaUtil.jsEncrypt.setPublicKey(publicKey.replace("\r\n|\n", ""));
      return RsaUtil.jsEncrypt.encryptLong(encodeURIComponent(text));
    } catch (e) {
      return text;
    }
  };

  /**
   * js解密
   *
   * @param text 密文
   * @param privateKey 响应私钥
   * @returns {string} 解密后的明文
   */
  static decrypt = (text: string, privateKey: string): string => {
    if (text === "" || text === null || text === undefined || text === "null") {
      return text;
    }
    try {
      console.log("RsaUtil.jsEncrypt.encryptLong", RsaUtil.jsEncrypt);
      RsaUtil.jsEncrypt.setPrivateKey(privateKey.replace("\r\n|\n", ""));
      const decryptText = RsaUtil.jsEncrypt.decryptLong(text);
      if (
        decryptText === null ||
        decryptText === "" ||
        decryptText === undefined ||
        decryptText === "null"
      ) {
        return text;
      }
      return decodeURIComponent(decryptText);
    } catch (e) {
      return text;
    }
  };
}
